import logging

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from comment.comviews import com_views, server_time
from .models import User
import json
from comment.log_code import LogCodes
from utils.tokens import *
from django.http import QueryDict


class UserView(View):
    def get_data(self, request, data, params):
        body = json.loads(request.body)
        for param in params:
            data[param] = body.get(param, None)
        return data
    
    def get(self, requests):
        # 根据id获得用户
        ret = {}
        id = requests.GET.get("id")
        if id is None:
            message = "params is not full"
            code = LogCodes.PARAMS_EMPTY
        user = User.objects.get(id=id)
        if user is None:
            message = "params is not full"
            code = LogCodes.SELECT_ERROR
        else:
            message = "success"
            code = LogCodes.SELECT_OK
            ret["data"] = str(user)
        
        ret["message"] = message
        ret["err_code"] = code
        return JsonResponse(ret)
    
    def put(self, request):
        # 创建用户
        ret = {}
        data = {}
        try:
            token = request.POST.get("token", None)
            body = json.loads(request.body)
            data['name'] = body.get("name", None)
            data['email'] = body.get('email', None)
            data['phone'] = body.get('phone', None)
            data['main_password'] = body.get('password', None)
        except Exception as e:
            ret["message"] = "params is error"
            ret["err_code"] = LogCodes.PARAMS_ERROR
            return JsonResponse(ret)
        if self.params_empty(data):
            ret["message"] = "params is not full"
            ret["err_code"] = LogCodes.PARAMS_ERROR
            return JsonResponse({"state_code": LogCodes.UPDATE_ERROR})
        user = User.find_by_name(data.get("name"))
        if user is None:
            return JsonResponse({"state_code": LogCodes.UPDATE_ERROR})
        
        for key, value in data.items():
            user.__setattr__("key", value)
        try:
            user.save()
            message = "success"
            code = LogCodes.UPDATE_OK
        except Exception as e:
            message = "update is error"
            code = LogCodes.UPDATE_ERROR
        ret["message"] = message
        ret["err_code"] = code
        return JsonResponse(ret)
    
    def post(self, requests):
        # 修改用户
        ret = {}
        data = {}
        # token = requests.POST.get["token"]
        data['name'] = requests.POST.get('name')
        data['email'] = requests.POST.get('email')
        data['phone'] = requests.POST.get('phone')
        data['main_password'] = requests.POST.get('password')
        
        if self.params_empty(data):
            ret["message"] = "params is error"
            ret["err_code"] = LogCodes.PARAMS_ERROR
            return JsonResponse(ret)
        if User.find_by_name(data.get("name")):
            ret["message"] = "params is error"
            ret["err_code"] = LogCodes.PARAMS_ERROR
            return JsonResponse(ret)
        try:
            
            user = User.objects.create(**data)
            if user != None:
                code = LogCodes.CREATE_OK
                message = ""
                ret["data"] = {"id": user.id}
            else:
                code = LogCodes.CREATE_ERROR
                message = "create is error"
        except Exception as e:
            code = LogCodes.CREATE_ERROR
            message = "create is error"
        
        ret["message"] = message
        ret["err_code"] = code
        return JsonResponse(ret)
    
    @staticmethod
    def params_empty(data):
        if not isinstance(data, dict):
            return False
        if not all([d for k, d in data.items()]):
            return True
        else:
            return False


def params_empty(data):
    if not isinstance(data, dict):
        return False
    if not all([d for k, d in data.items()]):
        return True
    else:
        return False


def id_get_user(params):
    # 根据id获得用户
    data = None
    id = params.get("id")
    if id is None:
        message = "params is not full"
        code = LogCodes.PARAMS_EMPTY
        return [code, message, data]
    user = User.objects.get(id=id)
    if user is None:
        message = "params is not full"
        code = LogCodes.SELECT_ERROR
    else:
        message = "success"
        code = LogCodes.SELECT_OK
        data = str(user)
    
    return [code, message, data]


def user_create(params):
    # 创建用户
    data = {}
    try:
        data['name'] = params.get("name", None)
        data['email'] = params.get('email', None)
        data['phone'] = params.get('phone', None)
        data['main_password'] = params.get('password', None)
    except Exception as e:
        message = "params is error"
        code = LogCodes.PARAMS_ERROR
        return [code, message, data]
    if params_empty(data):
        message = "params is not full"
        code = LogCodes.PARAMS_ERROR
        return [code, message, data]
    user = User.find_by_name(data.get("name"))
    if user is None:
        message = "user is empty"
        code = LogCodes.SELECT_ERROR
        return [code, message, data]
    
    for key, value in data.items():
        user.__setattr__("key", value)
    try:
        user.save()
        message = "success"
        code = LogCodes.UPDATE_OK
    except Exception as e:
        message = "update is error"
        code = LogCodes.UPDATE_ERROR
    return [code, message, data]


def user_update(params):
    # 修改用户
    ret = {}
    data = {}
    # token = requests.POST.get["token"]
    data['name'] = params.get('name')
    data['email'] = params.get('email')
    data['phone'] = params.get('phone')
    data['main_password'] = params.get('password')
    
    if params_empty(data):
        ret["message"] = "params is error"
        ret["err_code"] = LogCodes.PARAMS_ERROR
        return JsonResponse(ret)
    if User.find_by_name(data.get("name")):
        ret["message"] = "params is error"
        ret["err_code"] = LogCodes.PARAMS_ERROR
        return JsonResponse(ret)
    try:
        
        user = User.objects.create(**data)
        if not user is None:
            code = LogCodes.CREATE_OK
            message = ""
            ret["data"] = {"id": user.id}
        else:
            code = LogCodes.CREATE_ERROR
            message = "create is error"
    except Exception as e:
        code = LogCodes.CREATE_ERROR
        message = "create is error"
    
    ret["message"] = message
    ret["err_code"] = code
    return JsonResponse(ret)


def user_list(params):
    """用户列表"""
    data = None
    id = params.get("id")
    admin = User.objects.get(id=id).is_admin
    if admin:
        message = ""
        code = LogCodes.LOGIN_ERROR
        success = 0
    else:
        users = User.objects.get(id=id)
        data = list(users)
        message = ""
        code = LogCodes.LOGIN_ERROR
        success = 1
    return [code, message, data, success, server_time()]


def sign_in(params):
    """注册"""
    data = None
    name = params.get("name")
    password = params.get("password")
    email = params.get("email")
    phone = params.get("phone")
    if not all([name, password, email, phone]):
        message = "params is not full"
        code = LogCodes.SELECT_ERROR
        success = 0
    else:
        user = User.create_user(name, password, email, phone)
        if user is None:
            message = "sign in error"
            code = LogCodes.CREATE_ERROR
            success = 0
        else:
            message = "success"
            code = LogCodes.CREATE_OK
            success = 1
    return [code, message, data, success, server_time()]


def login(params):
    """登陆"""
    data = None
    name = params.get("name")
    password = params.get("password")
    
    if not all([name, password]):
        message = "params is not full"
        code = LogCodes.SELECT_ERROR
        return [message, code, None, 0, server_time()]
    try:
        user = User.objects.get(name=name)
    except Exception as e:
        logging.error(e)
        return ["params is not full", LogCodes.SELECT_ERROR, None, 0, server_time()]
    if user.main_password != password:
        message = "password is error"
        code = LogCodes.PARAMS_ERROR
        success = 0
    else:
        message = "success"
        code = LogCodes.SELECT_OK
        success = 1
        uid = user.uid
        data = {"token": create_token(uid, name, password)}
    return [code, message, data, success, server_time()]


def index(request):
    return com_views(request, {
        "login": login,
        "signin": sign_in,
        "userList": user_list,
        "userUpdate": user_update,
        "getUserById": id_get_user,
        "userCreate": user_create
    })
